package com.alpha.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.alpha.dao.QuestionDao;

/**
 * Servlet implementation class SaveQuestionsServlet
 */
@WebServlet("/SaveQuestionsServlet")
@ServletSecurity(@HttpConstraint(rolesAllowed = {"admin"}))
public class SaveQuestionsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(SaveQuestionsServlet.class.getName());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SaveQuestionsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		logger.info(this.getClass().getSimpleName()+" post method started.");
		
		int exam_id = -1;
		String[] question_ids = null;
		boolean successful = false;
		
		if(request.getParameter("exam_id")!=null){
			exam_id = Integer.parseInt(request.getParameter("exam_id"));
		}
		
		if(request.getParameterValues("case")!=null){
			question_ids = request.getParameterValues("case");
		}
		QuestionDao qDao = new QuestionDao();
		
		if (question_ids!=null) {
			for (int i = 0; i < question_ids.length; i++) {
				try {
					if (qDao.insertQuestionToExam(
							Integer.valueOf(question_ids[i]), exam_id)) {
						successful = true;
					} else {
						successful = false;
					}
				} catch (NumberFormatException e) {
					logger.error(e.getMessage());
					return;
				} catch (NamingException e) {
					logger.error(e.getMessage());
					return;
				} catch (SQLException e) {
					logger.error(e.getMessage());
					return;
				}
			}
		}
		
		if(successful){
			response.sendRedirect("ExamsAdminServlet?success=Adding+Question/s+Successful!");
			return;
		}else{
			response.sendRedirect("ExamsAdminServlet?error=Adding+Question/s+Failed!");
			return;
		}
	}

}
